﻿// ==UserScript==
// @name       form-filler
// @namespace  http://use.i.E.your.homepage/
// @version    0.1
// @description  enter something useful
// @match        https://localhost:44300/Home.htm
// @require      https://user-web.googlecode.com/svn/trunk/Scripts/jquery/jquery-2.1.0.js
// @copyright  2012+, You
// ==/UserScript==
$(function () {
    if (document.location.href.match(/localhost/)) {

        $(document).bind("dblclick", function (e) {
            if (e.shiftKey) {
                Common.Log("shift+dblclick - Filling form...");
                DevFill();
                Common.ClearSelection();
            }
            else if (e.ctrlKey) {
                Common.Log("ctrl+dblclick - Saving form...");

                var $button = $("input[value='Save']:first");

                if ($button.length == 0) {
                    $button = $("input[type='submit']:first");
                }

                $button.click();
                Common.ClearSelection();
            }
        });

        function DevFill() {
            var filler = new FormFiller().Fill();
        }

        setTimeout(function () {
            DevFill();
        }, 100);
    }
});

var Common = {
    //concatenate strings - faster than string + string
    Concat: function () {
        var sb = [];

        for (var i = 0; i < arguments.length; i++) {
            sb.push(arguments[i]);
        }

        return sb.join("");
    },

    //return a random int from 0 to {length}
    GetRandomInt: function (length) {
        return Math.floor(Math.random() * length);
    },

    ZeroFill: function (number, width) {

        width -= number.toString().length;

        if (width > 0) {
            return new Array(width + (/\./.test(number) ? 2 : 1)).join('0') + number;
        }

        return number + ""; // always return a string
    },

    ClearSelection: function () {
        if (window.getSelection) {
            if (window.getSelection().empty) {  // Chrome
                window.getSelection().empty();
            } else if (window.getSelection().removeAllRanges) {  // Firefox
                window.getSelection().removeAllRanges();
            }
        } else if (document.selection) {  // IE
            document.selection.empty();
        }
    },

    Log: function (text1, text2) {
        if (window.console == null) {
            return;
        }

        if (text2 != null) {
            if (text1.length < 20) {
                text1 = text1 + Array(21 - text1.length).join(" ");
            }

            console.log("[form-filler] " + text1 + ": " + text2);
        }
        else {
            console.log("[form-filler] " + text1);
        }
    }
};

/* FormFiller ---------------------------------------------------------------------------- */

function FormFiller() {
    var me = this;

    me.Enabled = 1;

    var d = new Date();
    me.Timestamp = Common.Concat(Common.ZeroFill(d.getHours(), 2), ":", Common.ZeroFill(d.getMinutes(), 2), ":", Common.ZeroFill(d.getSeconds(), 2));

    me.Fill = function () {
        Common.Log("filling");
        var inputs = $("body").find("input[type='text'],input[type='radio'],input[type='checkbox'],textarea,select");

        if (inputs.length == 0) {
            Common.Log("no textboxes found!");
            return;
        }

        var firstDay = Common.GetRandomInt(10) + 1;

        for (var i = 0; i < inputs.length; i++) {
            var $input = $(inputs[i]);

            if ($input.prop("type") == "radio") {
                var radios = $("input[name='" + $input.prop("name") + "']");

                if (!radios.prop("checked")) {
                    var j = Common.GetRandomInt(radios.length);
                    $(radios[j]).prop("checked", true);
                }

                continue;
            }
            else if ($input.prop("type") == "checkbox") {
                var j = Common.GetRandomInt(99);

                if (j >= 50) {
                    $input.prop("checked", true);
                }

                continue;
            }

            if ($input.val() != "") {
                continue;
            }

            $input.removeAttr("disabled", "disabled");

            if ($input.attr("data-datepicker") == "true") {
                $input.val(Common.DateToDmyString(new Date(2012, 10, firstDay)));
                firstDay++; //start, end and live should be in order (hopefully the inputs collection will be in order)
            }
            else if ($input.is("select")) {
                var items = $input.find("option");
                
                if (items.length == 0 && $input.attr("id") == "Dto_ProjectManager_UserId") {
                    var opt = $("<option />", { value: "100000" + Common.GetRandomInt(9), text: "Test User" });
                    opt.prependTo($input);
                }
                else if (items.length > 1) {
                    $input.val(items[Common.GetRandomInt(items.length - 1) + 1].value);
                }
            }
            else if ($input.attr("data-val-number") != null) {
                $input.val(Common.GetRandomInt(5));
            }
            else if ($input.is("textarea")) {
                $input.val(Common.Concat(me.GetRandomText(50), " [", me.Timestamp, "]"));
            }
            else {
                $input.val(Common.Concat(me.GetRandomText(3), " [", me.Timestamp, "]"));
            }
        }

        return me;
    };

    me.Submit = function () {
        Common.Log("submitting");
        $("input[value='Save']:first").click();
    };

    me.GetRandomText = function (numberOfWords) {
        var words = "Lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua Ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur Excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est laborum"
            .split(' ');

        var sb = [];

        for (var i = 0; i < numberOfWords; i++) {
            var word = words[Common.GetRandomInt(words.length)]
            sb.push(word);
            //sb.push(" ");
        }

        var text = $.trim(sb.join(' ').toLowerCase());
        return text.substring(0, 1).toUpperCase() + text.substring(1).toLowerCase();
    };
};